package com.hatricks.is.capturecode;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.aliyun.dysmsapi20170525.models.SendSmsResponse;
import com.aliyun.dysmsapi20170525.models.SendSmsResponseBody;
import com.aliyun.teautil.models.RuntimeOptions;
import com.hatricks.is.exceptionstrace.BizException;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;

@Slf4j
public class MessageSend {

    public static final String SIGN_NAME = "海啦啦科技";

    @SneakyThrows
    public static com.aliyun.dysmsapi20170525.Client createClient() {
        com.aliyun.teaopenapi.models.Config config = new com.aliyun.teaopenapi.models.Config()
                .setAccessKeyId("LTAI5tRSBA8WpCVcZeHu6DYu")
                .setAccessKeySecret("LEMYp0yOcy6slU0799885sVr8lwqfj")
                .setEndpoint("dysmsapi.aliyuncs.com");
        return new com.aliyun.dysmsapi20170525.Client(config);
    }

    public static void sendMessage(String captureCode, String phoneNumber, TemplateEnums templateEnums) {
        com.aliyun.dysmsapi20170525.Client client = MessageSend.createClient();
        JSONObject json = new JSONObject();
        json.put("code", captureCode);
        com.aliyun.dysmsapi20170525.models.SendSmsRequest sendSmsRequest = new com.aliyun.dysmsapi20170525.models.SendSmsRequest()
                .setSignName(SIGN_NAME)
                .setTemplateCode(templateEnums.getValue())
                .setPhoneNumbers(phoneNumber)
                .setTemplateParam(json.toJSONString());
        try {
            // 复制代码运行请自行打印 API 的返回值
            SendSmsResponse sendSmsResponse = client.sendSmsWithOptions(sendSmsRequest, new RuntimeOptions());
            SendSmsResponseBody body = sendSmsResponse.getBody();
            String code = body.getCode();
            if (!"OK".equals(code)) {
                throw new BizException("验证码发送失败,失败原因为:" + body.getMessage());
            }
            System.out.println(JSON.toJSONString(sendSmsResponse));        } catch (Exception error) {
            throw new RuntimeException("当前发送短信失败,失败信息为" + error.getMessage());
        }
    }

    public static void main(String[] args) {
        sendMessage("111333", "15710481857", TemplateEnums.LOGIN_TEMPLATE);
    }
}

